
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const loggerMorgan = require('morgan');
const mongoose = require('mongoose')
const LoadRoute = require('./routes');
const config = require('./config');
const Result = require('./utils/Result');

const logger = require('./log')('app')

const app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));

app.use(loggerMorgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

new LoadRoute(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  Result.errorCode(res, 404, 'API not found!')
});

// error handler
app.use(function(err, req, res, next) {
  
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  Result.error(res, err.message)
});

// mongoose
dbConnect();

// start listening
function listen() {
  if (app.get('env') === 'test') return;
  app.listen(config.port);
  logger.info('server listening on ' + config.port)
}

// mongodb connect
function dbConnect() {
  mongoose.connection.on("error", loggerMorgan)
  .on('disconnected', dbConnect)
  .on('open', listen);
  return mongoose.connect(config.mongodb.uri, config.mongodb.options);
}

module.exports = app;
